import { App, Config, Init, Provide } from '@midwayjs/decorator'
import { Application } from 'egg'

import { createTransport } from 'nodemailer'
import { htmlToText } from 'html-to-text'

@Provide()
export class EmailService {

  protected transporter: any

  @App()
  app: Application

  @Config('email')
  emailConfig: any

  @Init()
  async init() {
    this.transporter = createTransport(this.emailConfig)
  }

  async send(to, subject, html) {
    const info = await this.transporter.sendMail({
      from: this.emailConfig.auth.user,
      to,
      subject,
      text: htmlToText(html, { wordwrap: 130 }),
      html
    })

    this.app.logger.info(`Message sent: ${info.messageId}`)
  }
}
